import { getOssSecurity, upDetail } from '@/services/ant-design-pro/source';
import { InboxOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { ActionType, ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, Upload, UploadFile, UploadProps, message } from 'antd';
import Dragger from 'antd/es/upload/Dragger';
import { FC, useState } from 'react';
import OSS from 'ali-oss';
import dayjs from 'dayjs';
import { AesDecrypt } from '@/utils/aes';
import { fill, set, update } from 'lodash';
import pages from '@/locales/bn-BD/pages';

interface CreateFormProps {
  reload?: ActionType['reload'],
  param?: any,
  values?: any,
}

const CreateForm: FC<CreateFormProps> = (props) => {
  const { reload, param, values } = props;
  const [source, setSource] = useState<string>(values.source);
  const [cover, setCover] = useState<string>(values.cover);
  const [fileCoverList, setFileCoverList] = useState<UploadFile[]>(values.cover === null ? [] :[
    {
      uid: '-1',
      name: values.cover,
      status: 'done',
      url: values.cover,
    },
  ]);
  const [fileList, setFileList] = useState<any>([{
    id: values.id, 
    name: values.source, 
    source: values.souce,
    status: 'done',
  }])
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    maxCount:1,
    beforeUpload(file, fileList) {
      const isPdf  = file.type === 'application/pdf';
      if (!isPdf) {
        message.error(`请上传pdf文件`);
      }
      return isPdf;
    },
    onChange(info) {
      const {file} = info;
      const { status } = file;
      const {typeId ,booksId, id} = param;
      const date = dayjs(new Date().getTime()).format('YYYYMM');
      const fileNameArray = file.name.split('.');
      const name = encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-4);
      if(file.type == "application/pdf"){
        setFileList([
          {
            id: fileList.length + 1, 
            name: fileNameArray[0], 
            url: `https://ky-data.oss-cn-shenzhen.aliyuncs.com/books/source/${typeId}/${booksId}/${id}/${date}`+ name + '.' + fileNameArray[fileNameArray.length - 1],
            status: status,
          }
        ]);
      }
      if (status === "removed") {
        setFileList([]);
      }
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
  };

  const [messageApi, contextHolder] = message.useMessage();
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const { run, loading } = useRequest(upDetail, {
    manual: true,
    onSuccess: () => {
      messageApi.success('更新成功');
      reload?.();
    },
    onError: () => {
      messageApi.error('更新失败!');
    },
  });
  const uploadOss = async (e:any) =>{
    const { typeId ,booksId, id} = param;
    const {obj} = await getOssSecurity();
    const ossDt = JSON.parse(AesDecrypt(obj));
    const tempFilePath = e.file.name;
    const index = tempFilePath.lastIndexOf('.');
    const fileNameArray = tempFilePath.split('.');
    console.log(encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-4));
    const suffix = tempFilePath.substr(index + 1);
    const random = encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-4);
    const fileName = random+'.'+suffix;
    const date = dayjs(new Date().getTime()).format('YYYYMM');
    const client = new OSS({
      region: 'oss-cn-shenzhen',
      bucket: 'ky-data',
      accessKeyId: ossDt.accessKeyId,
      accessKeySecret: ossDt.accessKeySecret,
      stsToken: ossDt.securityToken,
      secure: true,
    });
    const {res, name, url} = await client.put(`/books/source/${typeId}/${booksId}/${id}/${date}`+fileName, e.file);
    if(res.status === 200){
      const upFile = fileList;
      upFile[0].status = 'done';
      setFileList(upFile);
      setSource(url);
    }
  }
  const uploadCoverOss = async (e:any) =>{
    const { typeId ,booksId, id} = param;
    const {obj} = await getOssSecurity();
    const ossDt = JSON.parse(AesDecrypt(obj));
    const tempFilePath = e.file.name;
    const index = tempFilePath.lastIndexOf('.');
    const fileNameArray = tempFilePath.split('.');
    console.log(encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-11));
    const suffix = tempFilePath.substr(index + 1);
    const random = encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-11);
    const fileName = random+'.'+suffix;
    const date = dayjs(new Date().getTime()).format('YYYYMM');
    const client = new OSS({
      region: 'oss-cn-shenzhen',
      bucket: 'ky-data',
      accessKeyId: ossDt.accessKeyId,
      accessKeySecret: ossDt.accessKeySecret,
      stsToken: ossDt.securityToken,
      secure: true,
    });
    if(e.file.type.includes('image')){
      const {res, name, url} = await client.put(`/cover/${date}/`+fileName, e.file);
      const localUrl = window.URL.createObjectURL(e.file)
      if(res.status === 200){
        setFileCoverList([
          {
            uid: '1',
            name: name,
            status: 'done',
            url: localUrl,
          },
        ])
        setCover(`/cover/${date}/`+fileName);
      }
    }
  }
  const changeCover = (info:any)=>{
      const {file} = info;
      const { status } = file;
      const date = dayjs(new Date().getTime()).format('YYYYMM');
      const fileNameArray = file.name.split('.');
      const name = encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-11)
      // setCover(`/cover/${date}/`+name+'.'+ fileNameArray[fileNameArray.length-1] );
      if (status === 'removed') {
        setFileCoverList([]);
        setCover('');
      }
  }
  const beforeCoverUpload = (file: any, fileList:any) => {
    const isPdf  = (file.type.includes('image'));
    if (!isPdf) {
      message.error(`请上传png/jpg/jpeg文件`);
    }
    return isPdf;
  }
  return (
    <>
      {contextHolder}
      <ModalForm
        title={'修改资源'}
        trigger={
          <Button type="link">
            修改
          </Button>
        }
        width="400px"
        modalProps={{ okButtonProps: { loading }, destroyOnClose: true, onCancel:()=>{reload?.();}}}
        onFinish={async (value) => {
          const params = { 
            source: values.source === source ? '' : source, 
            name:value.name, 
            detail: value.detail, 
            page: value.page, 
            cover: values.cover === cover ? '' : cover, 
            id: values.id, 
            sort: values.sort, 
            status: value.status.value 
          }
          await run(params);
          return true;
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.ruleName"
                  defaultMessage="Rule name is required"
                />
              ),
            },
          ]}
          width="md"
          name="name"
          label= '资源名称'
          initialValue={values.name}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.ruleName"
                  defaultMessage="Rule name is required"
                />
              ),
            },
          ]}
          width="md"
          name="detail"
          label= '简介'
          initialValue={values.detail}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.ruleName"
                  defaultMessage="Rule name is required"
                />
              ),
            },
          ]}
          width="md"
          name="page"
          label= '页数'
          initialValue={values.page}
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.ruleName"
                  defaultMessage="Rule name is required"
                />
              ),
            },
          ]}
          label='状态'
          width="md"
          name="status"
          initialValue={{label: values.status === 1 ? '开启' : '关闭', value: values.status}}
          request={async () => {
            return [
              {label: '开启', value: 1},
              {label: '关闭', value: 0}
            ]
          }}
        />
        <div>资源：</div>
        <Dragger {...uploadProps} customRequest={uploadOss} fileList={fileList}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
          <p className="ant-upload-hint">支持单次或批量上传</p>
        </Dragger>
        <div style={{marginTop: 10, marginBottom: 10}}>封面：</div>
        <Upload
          customRequest = {uploadCoverOss}
          onChange={(info) => {changeCover(info)}}
          maxCount={1}
          fileList={fileCoverList}
          listType='picture'
          beforeUpload={(file, fileList)=>{beforeCoverUpload(file, fileList)}}
        >
          <Button icon={<UploadOutlined />}>上传封面</Button>
        </Upload>
      </ModalForm>
    </>
  );
};

export default CreateForm;

